package com.billdowney.qq.robot.sub.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * @author BillDowney
 */
@Api(tags = "截屏操作接口")
@RequestMapping(path = "screenshot", method = {RequestMethod.POST, RequestMethod.GET})
@RestController
@Slf4j
public class ScreenshotController {

    @RequestMapping(path = "realtime", produces = MediaType.IMAGE_JPEG_VALUE)
    @ApiOperation(value = "获取实时屏幕截图")
    public ResponseEntity<byte[]> start() {
        try {
            // 创建一个Robot对象
            Robot robot = new Robot();
            // 获取屏幕的大小
            Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
            // 创建一个Rectangle对象，用于指定截屏的区域
            Rectangle rectangle = new Rectangle(dimension);
            // 捕获屏幕上的内容
            BufferedImage bufferedImage = robot.createScreenCapture(rectangle);
            // 将捕获的内容保存到文件
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", out);
            return ResponseEntity.ok(out.toByteArray());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }
}
